package com.sx.sx1.service.impl;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.sx.sx1.domain.EastErrorListYBX;
import com.sx.sx1.service.SyncYBXService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

@Service
public class SyncYBXServiceImpl implements SyncYBXService {

     /*
sftmphost: 192.168.100.107
sftpport: 22
sftpusername: king
sftppassword: 123456
sftpremotePath: /picclife/nas/000100/east    #/picclife/nas/000100/east/1320   1320 是目录名，也是任务号，下面存放问题数据文件
#  sftp本地路径ruoyi.profle.ybx下

 */

    @Value("${sftmphost}")
    private String sftmphost;

    @Value("${sftpport}")
    private int sftpport;

    @Value("${sftpusername}")
    private String sftpusername;

    @Value("${sftppassword}")
    private String sftppassword;
    @Value("${sftpremotePath}")
    private String sftpremotePath;




    @Override
    public Integer readerRemoteDirAndFile(String remoteDir, Integer jobid) {
      //  jhgj_data_source jhobj = ybxMapper.findybxDS(jobid);
        String ybx_userid = "123";
        String sjbpch = "999999";

        Integer cnt = 0;

//        if( cnt != null && cnt > 0) {
//            log.info(jobid+" 的问题数据已经存储了。。");
//            return null;
//        }
//        log.info(jobid+" 的问题数据开始插入");
        //readerRemoteDirAndFile(remoteDir,jobid,ybx_userid,sjbpch );

//    }
//
//    public  void readerRemoteDirAndFile( String remoteDir,Integer jobid, String ybx_userid ,String sjbpch) {
        String host = sftmphost;
        int port = sftpport;
        String user = sftpusername;
        String password = sftppassword;
        //String remoteDir = "/data/ruoyi/upload/1319";

        JSch jsch = new JSch();
        Session session = null;
        Channel channel = null;
        ChannelSftp sftpChannel = null;

        try {
            // Setup JSch session.
            session = jsch.getSession(user, host, port);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect();

            // Open SFTP channel.
            channel = session.openChannel("sftp");
            channel.connect();
            sftpChannel = (ChannelSftp) channel;

            // Change to the remote directory.
            sftpChannel.cd(remoteDir);

            // List the files in the remote directory.
            Vector<ChannelSftp.LsEntry> list = sftpChannel.ls("*");
            List<String> emptyFiles = new ArrayList<>();
            List<String>  notemptyFiles = new ArrayList<>();

            List<EastErrorListYBX> inserts = new ArrayList<>();
            boolean hasQSdata = false;
            for (ChannelSftp.LsEntry entry : list) {
                String filename = entry.getFilename();


                // Read the file content.
                InputStream is = sftpChannel.get(filename);
                // Do something with the input stream, for example, print it.
                // Or, save it to a local file.
                // is.close();


                StringBuilder builder = new StringBuilder();
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        // builder.append(line).append('\n');
                        //  System.out.println(line);
                        //---


                        // 处理每一行数据
                        //System.out.println(line);

                        String[] strs =  line.split("\\|");
                        // for (int i = 0; i < strs.length; i++) {
                        //    System.out.print(i+":"+strs[i]+"       ");
                        // }

                        EastErrorListYBX eobj = new EastErrorListYBX();
                        eobj.setTable_code(strs[0]);
                        eobj.setTable_name_cn(strs[1]);
                        eobj.setData_code(strs[2]);
                        eobj.setData_name(strs[3]);
                        eobj.setRule_id(strs[4]);
                        eobj.setError_desc(strs[5]);
                        String lsh = strs[6];

                        String prefix = "LSH:";

                        boolean startsWith = lsh.startsWith(prefix);
                        if(startsWith){
                            lsh= lsh.substring(4,lsh.length());
                        }
                        eobj.setLsh(lsh);
                        eobj.setQingdan("");
                        eobj.setJob_id(jobid);

                        eobj.setYbx_userid(ybx_userid);
                        eobj.setSjbspch(sjbpch);
                        eobj.setRule_flag(jobid+"");

                        inserts.add(eobj);


                        if(inserts.size() ==1000){
                           // ybxMapper.addeast_error_list_ybx(inserts);
                            //ybxMapper.addeast_error_list_ybx_oracle(inserts);
                            inserts.clear();
                            hasQSdata = true;
                        }
                        //System.out.println("文件名："+f.getAbsolutePath());
                        //System.out.println(inserts);
                        //return;

                        //---
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (builder.length() > 0 && builder.charAt(builder.length() - 1) == '\n') {
                    // 判断去掉最后一个换行符
                    builder.setLength(builder.length() - 1);
                }
                //System.out.println(builder);

//                if(builder.length() ==0) {
//                    emptyFiles.add(filename);
//                }else{
//                    notemptyFiles.add(filename);
//                }
            }

            if(inserts.size() >0){
              //  ybxMapper.addeast_error_list_ybx(inserts);
               // ybxMapper.addeast_error_list_ybx_oracle(inserts);
                System.out.println("问题数据  插入oracle");
                inserts.clear();
                hasQSdata = true;
            }


            //System.out.println(notemptyFiles);
            if(hasQSdata) return jobid;   //有问题数据
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftpChannel != null) {
                sftpChannel.exit();
            }
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }

        return null;
    }
}
